<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/9/11
 * Time: 19:37
 */

namespace App\HttpController\Home;


use App\Enums\UrlEnums;
use App\Library\Auth;
use App\Utility\Pool\MysqlObject;
use App\Utility\Pool\MysqlPool;
use EasySwoole\HttpClient\HttpClient;
use EasySwoole\MysqliPool\Mysql;

class Team extends Base
{
    /**
     * lol队伍列表
     * @return bool
     * @throws \EasySwoole\Mysqli\Exceptions\ConnectFail
     * @throws \EasySwoole\Mysqli\Exceptions\PrepareQueryFail
     * @throws \Throwable
     */
    public function lists()
    {
        $params = $this->request()->getQueryParams();
        if( !isset($params['game']) ){
            return $this->writeJson(0,[],'缺少game参数');
        }
        $page = $params['page'] ?? 1;
        $pageSize = $params['pageSize'] ?? 20;
        $table = "siam_{$params['game']}teams";
        $db = Mysql::defer('mysql');
        $lists = $db->get($table,[$pageSize * ($page  - 1), $pageSize]);
        return $this->writeJson(1,$lists,'请求成功');
    }

    /**
     * 队伍详情
     * @return bool
     * @throws \EasySwoole\Mysqli\Exceptions\ConnectFail
     * @throws \EasySwoole\Mysqli\Exceptions\PrepareQueryFail
     * @throws \Throwable
     */
    public function info()
    {
        $params = $this->request()->getQueryParams();
        if( !isset($params['game']) ){
            return $this->writeJson(0,[],'缺少game参数');
        }

        if( !isset($params['team_id']) ){
            return $this->writeJson(0,[],'缺少team_id参数');
        }
        $table = "siam_{$params['game']}player";
        $teamTable = "siam_{$params['game']}teams";

        $db = Mysql::defer('mysql');
        $players = $db->where('team_id',$params['team_id'])->get($table);
        $team =  $db->where('team_id',$params['team_id'])->getOne($teamTable);
        $team['players'] = $players;
        if( isset($team['nation']) ){
            $team['country'] = $team['nation'];
            unset($team['nation']);
        }
        return $this->writeJson(1,$team,'请求成功');
    }

    /**
     * 战队联赛统计
     * @return bool
     * @throws \EasySwoole\HttpClient\Exception\InvalidUrl
     */
    public function teamStats()
    {
        $params = $this->request()->getQueryParams();
        if( !isset($params['league_id']) ){
            return $this->writeJson(0,null,'缺少league_id参数');
        }
        if( !isset($params['team_id']) ){
            return $this->writeJson(0,null,'缺少team_id参数');
        }

        $url = UrlEnums::FJURL.UrlEnums::LOL_TEAM_LEAGUE_STAS."?league_id={$params['league_id']}&team_id={$params['team_id']}";
        $client = new HttpClient($url);
        list($s1, $s2) = explode(' ', microtime());
        $microtime = (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000); //毫秒时间戳
        $option = [
            'path'      => UrlEnums::LOL_TEAM_LEAGUE_STAS,
            'api_time'  => $microtime
        ];
        $header = Auth::getInstance()->header($option);
        $client->setHeaders($header,true,false);
        $response = $client->get();
        $content = $response->getBody();
        $data = json_decode($content,true);
        if( isset($data['code']) && $data['code'] == 200 && $data['data'] ){
            return $this->writeJson(1,$data['data'],'请求成功');
        }else{
            return $this->writeJson(0,null,$data['message']);
        }
    }

    /**
     * 战队综合资料
     * @return bool
     * @throws \EasySwoole\HttpClient\Exception\InvalidUrl
     */
    public function compositeStats()
    {
        $team_id = $this->request()->getQueryParam('team_id');
        if( !$team_id ){
            return $this->writeJson(0,null,'缺少team_id参数');
        }
        $url = UrlEnums::FJURL.UrlEnums::LOL_COMPOSITE_STAS."?team_id={$team_id}&version=2";
        $client = new HttpClient($url);
        list($s1, $s2) = explode(' ', microtime());
        $microtime = (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000); //毫秒时间戳
        $option = [
            'path'      => UrlEnums::LOL_COMPOSITE_STAS,
            'api_time'  => $microtime
        ];
        $header = Auth::getInstance()->header($option);
        $client->setHeaders($header,true,false);
        $response = $client->get();
        $content = $response->getBody();
        $data = json_decode($content,true);
        if( isset($data['code']) && $data['code'] == 200 && $data['data'] ){
            return $this->writeJson(1,$data['data'],'请求成功');
        }else{
            return $this->writeJson(0,null,$data['message']);
        }
    }

    /**
     * 获取战队排行
     * @return bool
     * @throws \EasySwoole\Component\Pool\Exception\PoolEmpty
     * @throws \EasySwoole\Component\Pool\Exception\PoolException
     * @throws \Throwable
     */
    public function ranking()
    {
        $game = $this->request()->getQueryParam('game');
        if( !$game ){
            return $this->writeJson(1,null,'缺少game参数');
        }
        $params = $this->request()->getQueryParams();
        $res = MysqlPool::invoke(function (MysqlObject $db)use($params){
            $page = $params['page'] ?? 1;
            $pageSize = $params['pageSize'] ?? 20;
            $lists = $db->join('siam_lolteams as t','t.team_id=s.team_id')
                ->groupBy('s.team_id')
                ->orderBy('sum_score','desc')
                ->get('siam_lolscore as s',[$pageSize * ($page  - 1), $pageSize],['sum(s.score) as sum_score','s.team_id','t.name','t.name_en','t.short_name','t.logo']);
            $count = $db->join('siam_lolteams as t','t.team_id=s.team_id')
                ->groupBy('s.team_id')
                ->count('siam_lolscore as s');
            return ['currentPage'=>$page,'total'=>$count,'data'=>$lists];
        });
        return $this->writeJson(1,$res,'请求成功');
    }

    /**
     * 战队赛事统计
     * @return bool
     * @throws \EasySwoole\HttpClient\Exception\InvalidUrl
     */
    public function teamMatchState()
    {
        $game = $this->request()->getQueryParam('game');
        $team_steam_id = $this->request()->getQueryParam('team_steam_id');
        if( !$team_steam_id ){
            return $this->writeJson(0,null,'缺少team_steam_id参数');
        }
        if( $game == 'dota' ){
            $url = UrlEnums::FJURL.UrlEnums::DOTA_TEAM_MATCH_INFO."?team_steam_id={$team_steam_id}";
            $client = new HttpClient($url);
            list($s1, $s2) = explode(' ', microtime());
            $microtime = (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000); //毫秒时间戳
            $option = [
                'path'      => UrlEnums::DOTA_TEAM_MATCH_INFO,
                'api_time'  => $microtime
            ];
        }else{
            return $this->writeJson(0,null,'暂时没有数据统计');
        }

        $header = Auth::getInstance()->header($option);
        $client->setHeaders($header,true,false);
        $response = $client->get();
        $content = $response->getBody();
        $data = json_decode($content,true);
        if( isset($data['code']) && $data['code'] == 200 && $data['data'] ){
            return $this->writeJson(1,$data['data'],'请求成功');
        }else{
            return $this->writeJson(0,null,$data['message']);
        }
    }

    /**
     * 战队玩家
     * @return bool
     * @throws \EasySwoole\Component\Pool\Exception\PoolEmpty
     * @throws \EasySwoole\Component\Pool\Exception\PoolException
     * @throws \Throwable
     */
    public function players()
    {
        $game = $this->request()->getQueryParam('game');
        $team_id = $this->request()->getQueryParam('team_id');
        if( !$game ){
            return $this->writeJson(0,null,'缺少game参数');
        }
        if( !$team_id ){
            return $this->writeJson(0,null,'缺少team_id参数');
        }
        $players = MysqlPool::invoke(function (MysqlObject $db)use($game,$team_id){
            $table = "siam_{$game}player";
            return $db->where('team_id',$team_id)->get($table);
        });
        return $this->writeJson(1,$players,'请求成功');
    }
}